import requests
from bs4 import BeautifulSoup
import json


# 改变cookies形式
def parse_cookie_string(cookie_string):
    cookies = {}
    items = cookie_string.split(';')  # 使用分号分割字符串
    for item in items:
        key_value = item.strip().split('=')  # 使用等号分割键值对
        if len(key_value) == 2:  # 确保键值对有两个元素
            key = key_value[0].strip()
            value = key_value[1].strip()
            cookies[key] = value
    return cookies


# 提取信息
def extract_information(response):
    try:
        if response.status_code == 200:
            soup = BeautifulSoup(response.text, 'html.parser')
            # 提取class名为“discountPrice-price”的div标签内容赋值给变量price
            price_element = soup.find('div', class_='discountPrice-price')
            price = price_element.text.strip() if price_element else None

            # 提取第二个class名为“next-tabs-tab-inner”的div标签内容赋值给变量comment
            comment_elements = soup.find_all('div', class_='next-tabs-tab-inner')
            comment = None
            if len(comment_elements) >= 2:
                comment = comment_elements[1].text.strip()
            return price, comment
        else:
            print("Failed to fetch the webpage. Status code:", response.status_code)
            return None, None
    except requests.RequestException as e:
        print("Error during requests to", url)
        print(str(e))
        return None, None


if __name__ == '__main__':

    original_cookies = ''   # 填入自己的cookies
    cookies_dic = parse_cookie_string(original_cookies)

    url = 'https://detail.1688.com/offer/566994949217.html'

    with open('./result.txt', 'r', encoding='utf-8') as file:
        html_content = file.read()
    soup = BeautifulSoup(html_content, 'html.parser')
    # 查找包含 window.__INIT_DATA 的 script 标签
    init_data_script = soup.find('script', text=lambda text: text and 'window.__INIT_DATA' in text)
    init_data_content = init_data_script.text.strip()
    init_data = init_data_content.split('window.__INIT_DATA=')[1]
    init_data = json.loads(init_data)
    items = init_data['data']['1081181309201']['data']

    for item in items:
        item_name = item['name']
        item_value = item['value']
        print(item_name, item_value)
